'''
Created on Jan 18, 2010

@author: eqijian
'''
from google.appengine.api import users
import os
from google.appengine.ext.webapp import template
from google.appengine.ext import webapp
from google.appengine.ext import db
from model import Post
from model import Music
from model import Picture
from model import Comment
import cgi
from Cookie import SmartCookie
from os import environ


import datetime
import logging

class BasePage(webapp.RequestHandler):
  """Supplies a common template generation function.

  When you call generate(), we augment the template variables supplied with
  the current user in the 'user' variable and the current webapp request
  in the 'request' variable.
  """
  def generate(self, template_name, template_values={}):
    values = {
      'user': users.get_current_user(),
      'login_url': users.create_login_url(self.request.uri),
      'logout_url': users.create_logout_url(self.request.uri),
      'application_name': 'WatsonBlog',
    }
    values.update(template_values)
    directory = os.path.dirname(__file__)
    path = os.path.join(directory, os.path.join('..',os.path.join('templates', template_name)))
    self.response.headers['Set-Cookie']='chips=ahoy\r\nSet-Cookie: vienna=finger'
    self.response.out.write(template.render(path, values))

      
def get_latest_updates(size = 10):
  latest_updates = []
  latest_updates.extend(Post.all().order('modified').fetch(size))
  return latest_updates       
       

def get_latest_posts(size = 10):
  latest_posts = []
  latest_posts.extend(Post.all().order('-modified').fetch(10))
  return latest_posts
       
class HomePage(BasePage):
  """ Home tab handler.
  """
  def get(self): 
    logging.debug(os.environ)
    cookies = SmartCookie(environ.get("HTTP_COOKIE",""))
    logging.debug(cookies)
    # Genertate the html page by template
    self.generate('home.html', {
      'curr_page' : 'Home',
      'latest_updates': get_latest_updates(),
      'latest_posts': get_latest_posts(),
    })

class ListPostPage(BasePage):
  """
     /post
     /post/
  """
  def get(self):
    self.generate('list_post.html',{
         'curr_page' : 'Post',
         'latest_posts' : get_latest_posts()
    })
  
class NewPostPage(BasePage):
  def get(self):
    self.generate('new_post.html',{
        'curr_page':'Post',
        'pid' : 'new',
        'title' : '',
        'content' : '',
      })
    
  def post(self):
    title = self.request.get('title')
    content = self.request.get('content')
    #create new post entity
    post = Post()
    post.created = datetime.datetime.now()
    post.modified = datetime.datetime.now()
    post.poster = users.get_current_user().email()
    post.title = title
    post.content = content
    key = post.put()
    self.response.out.write('/post/%s.html' % key)
    
class EditPostPage(BasePage):
  """
     /post/edit_234234.html
  """
  def get(self, pid):
    post = Post.get(pid)
    self.generate('edit_post.html', {
        'curr_page':'Post',
        'pid' : pid,
        'post' : post
      })

class PostPage(BasePage): 
  def get(self, pid):
    """
        /post/223422.html
        /post/2223232.html
    """ 
    post = Post.get(db.Key(pid))
    self.generate('post.html', {
        'curr_page' : 'Post',
        'mode' : 'edit',
        'pid' : pid,
        'post' : post
        })
  
  def post(self, pid):
    action = self.request.get('action')
    if action == 'delete':
      #create new post entity
      post = db.get(db.Key(pid))
      db.delete(post)
    elif action == 'update':
      title = self.request.get('title')
      content = self.request.get('content')
      logging.debug('-----title %s ' % title )
      logging.debug('-----content %s ' % content)
      post = db.get(db.Key(pid))
      post.title = title
      post.content = content
      post.modified = datetime.datetime.now()
      db.put(post)

class UploadPicPage(BasePage):
  def file_reader(self, file, n):
    """a generator which reads n bytes of file"""
    buf = file.read(n)
    while buf != '': 
      yield buf
      buf = file.read(n)
       
  def get(self):  
    self.generate('upload_pic.html', {
        'curr_page' : 'Pic',
        })
  
  def post(self):
    fs = cgi.FieldStorage()['pic_file']
    pic = Picture()
    pic.title = fs.filename
    pic.put()
    tmp = pic
    for data in self.file_reader(fs.file,1000):
      tmp.content = data
      new = Picture()
      tmp.next = new
      tmp.put()
      tmp = new

class Picture(BasePage):
  def get(self):
    pass
    
    
      
class PicPage(BasePage):
  def get(self):
    # Genertate the html page by template
    self.generate('home.html', {
      'curr_page' : 'Picture',
      'latest_updates': latest_updates,
      'latest_posts': self.get_latest_posts(),
    })
    
class MusicPage(BasePage):
  def get(self):
    latest_updates = self.get_latest_updates()
    for update in latest_updates:
      update.view_url = self.get_view_url(update)
    
    # Genertate the html page by template
    self.generate('home.html', {
      'curr_page' : 'Music',
      'latest_updates': latest_updates,
      'latest_posts': self.get_latest_posts(),
    })
    
class ProfilePage(BasePage):
  def get(self):
    latest_updates = self.get_latest_updates()
    for update in latest_updates:
      update.view_url = self.get_view_url(update)
    
    # Genertate the html page by template
    self.generate('home.html', {
      'curr_page' : 'Profile',
      'latest_updates': latest_updates,
      'latest_posts': self.get_latest_posts(),
    })
        
class RssPage(BasePage):
  def get(self):
    latest_updates = self.get_latest_updates()
    for update in latest_updates:
      update.view_url = self.get_view_url(update)
    
    # Genertate the html page by template
    self.generate('home.html', {
      'curr_page' : 'Rss',
      'latest_updates': latest_updates,
      'latest_posts': self.get_latest_posts(),
    })
  
class InvalidPage(BasePage):
  def get(self):
    self.error(404)
    self.generate('404.html')
    
  def post(self):
    self.error(404)
    self.generate('404.html')